/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package studio.raptor.ddal.core.transaction;


/**
 * 事务日志记录器。
 *
 * @author Sam
 * @since 3.0.0
 */
public class TransactionLogRecorder {

  private TransactionLogger txLogger = MainLineTransactionLogger.instance();
  private StringBuilder messageBuffer = new StringBuilder();
  private static final String MSG_SEPARATOR = "|";
  private static final String RECORDER_VERSION = "3.0.0.1000"; // todo：改成jar包获取版本


  public void record(String message) {
    this.messageBuffer.append(message).append(MSG_SEPARATOR);
  }

  /**
   * 日志增加版本标记
   */
  public void recordVersion() {
    record(RECORDER_VERSION);
  }

  public void record(String message, boolean noSeparator) {
    this.messageBuffer.append(message);
    if (!noSeparator) {
      this.messageBuffer.append(MSG_SEPARATOR);
    }
  }

  /**
   * 调用此方法前请确保缓存的消息已写入日志文件。从程序的效率角度出发，该方法
   * 不再对messageBuffer做空判断。
   *
   * @param transactionId 事务ID
   */
  public void recordTxCommit(String transactionId) {
    this.messageBuffer.append(transactionId).append(MSG_SEPARATOR).append("COMMIT");
    flush();
  }

  public void flush() {
    txLogger.log(messageBuffer.toString());
    clear();
  }

  public void clear() {
    this.messageBuffer = new StringBuilder();
  }

  /**
   * 切换到恢复模式。此方法只有事务恢复可以调用。
   */
  void switchToRecMode() {
    this.txLogger = MainLineTransactionLogger.instance();
  }
}
